package com.jianyun.jyzs.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hannesdorfmann.mosby3.mvp.MvpActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.adapter.CalendarAdapter;
import com.jianyun.jyzs.adapter.CrmCalendarListAdapter;
import com.jianyun.jyzs.bean.CrmCalendarCountBean;
import com.jianyun.jyzs.bean.CrmCalendarListBean;
import com.jianyun.jyzs.bean.DateInfo;
import com.jianyun.jyzs.presenter.CrmCalendarPrenter;
import com.jianyun.jyzs.utils.DateUtils;
import com.jianyun.jyzs.utils.FullDialogLoading;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.RceLog;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.view.iview.ICrmCaledarView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by yangshijun on 2018/6/4.
 * CRM日历预约功能
 */

public class CrmCalendarActivity extends MvpActivity<ICrmCaledarView, CrmCalendarPrenter> implements ICrmCaledarView {
    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText1)
    Button topText1;
    @BindView(R.id.topText2)
    Button topText2;
    @BindView(R.id.topClander)
    ImageView topClander;
    @BindView(R.id.iv_app_moreLinearLayout)
    LinearLayout ivAppMoreLinearLayout;
    @BindView(R.id.topCreat)
    LinearLayout topCreat;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.left_img)
    TextView leftImg;
    @BindView(R.id.btn_prev_month)
    LinearLayout btnPrevMonth;
    @BindView(R.id.tv_month)
    TextView tvMonth;
    @BindView(R.id.right_img)
    TextView rightImg;
    @BindView(R.id.btn_next_month)
    LinearLayout btnNextMonth;
    @BindView(R.id.calendar)
    RecyclerView calendarView;
    @BindView(R.id.loadButton)
    Button loadButton;
    @BindView(R.id.nullLinearLayout)
    LinearLayout nullLinearLayout;

    @BindView(R.id.orderList)
    RecyclerView crmRecyView;
    @BindView(R.id.tv_tabIndex)
    TextView tvTabIndex;



    private SimpleDateFormat yyyy_mm_dd;
    private Calendar baseCalendar;
    private ArrayList<DateInfo> dateList;
    private List<CrmCalendarCountBean.DataList> dataCunt = new ArrayList<>();
    private CalendarAdapter calendarAdapter;

    private int tagIndex = 1;//0 历史 1 预约
    private CrmCalendarListAdapter crmCalendarListAdapter;
    private String userId;
    private String enterpriseCode;
    private String year_month = "";
    private String workDate = "";
    private List<CrmCalendarListBean.ListBean> crmList = new ArrayList();
    private boolean isInit = true;
    private FullDialogLoading dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this, true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.crm_calendar_layout);
        ButterKnife.bind(this);
        initData();

    }

    @NonNull
    @Override
    public CrmCalendarPrenter createPresenter() {
        return new CrmCalendarPrenter();
    }


    private void initData() {
        dialog = FullDialogLoading.createDialog(this);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setMessage(getString(R.string.load_text));
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        baseCalendar = Calendar.getInstance();
        baseCalendar.setTime(new Date());
        crmRecyView.setLayoutManager(new LinearLayoutManager(this));
        crmCalendarListAdapter = new CrmCalendarListAdapter(this, null);
        crmRecyView.setAdapter(crmCalendarListAdapter);
        initCalendar(baseCalendar);
        initView();

    }

    private void initView() {
        topBack.setVisibility(View.VISIBLE);
        calendarView.setLayoutManager(new GridLayoutManager(this, 7));
        calendarAdapter = new CalendarAdapter(this, dateList);
        calendarView.setAdapter(calendarAdapter);

    }

    public void setCrmView(List<CrmCalendarListBean.ListBean> crmLists) {
        Log.i("test", "设置列表");
        if (crmLists != null && crmLists.size() > 0) {
            crmCalendarListAdapter.setList(crmLists);
            nullLinearLayout.setVisibility(View.GONE);
        } else {
            crmCalendarListAdapter.setList(null);
            nullLinearLayout.setVisibility(View.VISIBLE);
        }
    }

    public void setCalendarViewDateClick(String date) {
        Log.i("test", "点击日期：" + date);
        workDate = date;
        getPresenter().getCrmDateList(enterpriseCode, userId, tagIndex + "", date);
    }

    private void initCalendar(Calendar calendar) {

        dateList = new ArrayList<>();
        int year = calendar.get(Calendar.YEAR);
        String year_ = year + "";
        int month = calendar.get(Calendar.MONTH) + 1;
        tvMonth.setText(year + "年" + month + "月");
        if (month < 10) {
            year_month = year_ + "-" + "0" + month;
        } else {
            year_month = year_ + "-" + month;
        }
        String todaystring = DateUtils.YMD(new Date());
        getPresenter().getCrmMonthCount(enterpriseCode, userId, tagIndex + "", year_month);
        if (isInit) {
            workDate = todaystring;
            getPresenter().getCrmDateList(enterpriseCode, userId, tagIndex + "", workDate);
            isInit = false;
        }
        int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);//获得当前日期所在月份有多少天（或者说day的最大值)，用于后面的计算
        Calendar calendarClone = (Calendar) calendar.clone(); //克隆一个Calendar再进行操作，避免造成混乱
        calendarClone.set(Calendar.DAY_OF_MONTH, 1);  //将日期调到当前月份的第一天
        int startDayOfWeek = calendarClone.get(Calendar.DAY_OF_WEEK); //获得当前日期所在月份的第一天是星期几
        calendarClone.set(Calendar.DAY_OF_MONTH, maxDay); //将日期调到当前月份的最后一天
        int endDayOfWeek = calendarClone.get(Calendar.DAY_OF_WEEK); //获得当前日期所在月份的最后一天是星期几
      /*  String month_ = (month + "").length() > 1 ? (month + "") : "0" + month;
        String format = year_ + "-" + month_ + "-";
        for (int i = 0; i < maxDay; i++) {
            int d = i + 1;
            String day_ = (d + "").length() > 1 ? (d + "") : "0" + d;
//            List<CrmDetial.CrmDetailBean> calendarCrm = crmDao.getCalendarCrm(userId, enterpriseCode, format + day_, tagIndex);
//            RceLog.d("lml", "查询结果——————时间" + format + day_ + calendarCrm.toString());

        }*/
        //计算上一个月在本月日历页出现的那几天.
        //比如，startDayOfWeek = 3，表示当月第一天是星期二，所以日历向前会空出2天的位置，那么让上月的最后两天显示在星期日和星期一的位置上.
        int startEmptyCount = startDayOfWeek - 1; //上月在本月日历页因该出现的天数。
        Calendar preCalendar = (Calendar) calendar.clone();  //克隆一份再操作
        preCalendar.set(Calendar.DAY_OF_MONTH, 1); //将日期调到当月第一天
        preCalendar.add(Calendar.DAY_OF_MONTH, -startEmptyCount); //向前推移startEmptyCount天
        for (int i = 0; i < startEmptyCount; i++) {
            DateInfo dateInfo = new DateInfo(); //使用DateInfo来储存所需的相关信息
            dateInfo.setDate(preCalendar.getTime());
            dateInfo.setDayOfM(preCalendar.get(Calendar.DAY_OF_MONTH));
            dateInfo.setType(DateInfo.PRE_MONTH); //标记日期信息的类型为上个月
            dateList.add(dateInfo); //将日期添加到数组中
            preCalendar.add(Calendar.DAY_OF_MONTH, 1); //向后推移一天
        }
        /**
         * 计算当月的每一天日期
         */
        calendar.set(Calendar.DAY_OF_MONTH, 1); //由于是获取当月日期信息，所以直接操作当月Calendar即可。将日期调为当月第一天
        for (int i = 0; i < maxDay; i++) {
            DateInfo dateInfo = new DateInfo();
            dateInfo.setDate(calendar.getTime());
            dateInfo.setDayOfM(calendar.get(Calendar.DAY_OF_MONTH));
            dateInfo.setType(DateInfo.CURRENT_MONTH);  //标记日期信息的类型为当月

            String ymd = DateUtils.YMD(calendar.getTime());
            if (ymd.equals(todaystring)) {
                dateInfo.setToday(true);
            } else {
                dateInfo.setToday(false);
            }
            dateList.add(dateInfo);
            calendar.add(Calendar.DAY_OF_MONTH, 1); //向后推移一天
        }

        /**
         * 计算下月在本月日历页出现的那几天。
         * 比如，endDayOfWeek = 6，表示当月第二天是星期五，所以日历向后会空出1天的位置，那么让下月的第一天显示在星期六的位置上。
         */
        int endEmptyCount = 7 - endDayOfWeek; //下月在本月日历页上因该出现的天数
        Calendar afterCalendar = (Calendar) calendar.clone(); //同样，克隆一份在操作
        for (int i = 0; i < endEmptyCount; i++) {
            DateInfo dateInfo = new DateInfo();
            dateInfo.setDate(afterCalendar.getTime());
            dateInfo.setDayOfM(afterCalendar.get(Calendar.DAY_OF_MONTH));
            dateInfo.setType(DateInfo.AFTER_MONTH); //将DateInfo类型标记为下个月
            dateList.add(dateInfo);
            afterCalendar.add(Calendar.DAY_OF_MONTH, 1); //向后推移一天
        }
        this.baseCalendar.add(Calendar.MONTH, -1);
    }

    @OnClick({R.id.topBack, R.id.topText1, R.id.topText2, R.id.btn_prev_month, R.id.btn_next_month})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_prev_month:
                RceLog.d("lml", "btn_prev_month  前" + baseCalendar.toString());
                baseCalendar.add(Calendar.MONTH, -1);
                RceLog.d("lml", "btn_prev_month  后" + baseCalendar.toString());
                initCalendar(baseCalendar);
                setCrmView(null);
                break;
            case R.id.btn_next_month:
                RceLog.d("lml", "btn_next_month 前" + baseCalendar.toString());
                baseCalendar.add(Calendar.MONTH, 1);
                RceLog.d("lml", "btn_next_month 后" + baseCalendar.toString());
                initCalendar(baseCalendar);
                setCrmView(null);
                break;
            case R.id.topText1:
                topText1.setBackgroundResource(R.drawable.bg_aralm_relevant_false);//bg_aralm_relevant_false
                topText2.setBackgroundResource(R.drawable.bg_aralm_res_true);
                topText1.setTextColor(getResources().getColorStateList(R.color.white));
                topText2.setTextColor(getResources().getColorStateList(R.color.blue));
                tagIndex = 1;
                tvTabIndex.setText("预约沟通");
                initCalendar(this.baseCalendar);
                setCrmView(null);
                break;
            case R.id.topText2:
                topText2.setBackgroundResource(R.drawable.bg_aralm_res_false);//bg_aralm_res_false
                topText1.setBackgroundResource(R.drawable.bg_aralm_relevant_true);
                topText2.setTextColor(getResources().getColorStateList(R.color.white));
                topText1.setTextColor(getResources().getColorStateList(R.color.blue));
                tagIndex = 0;
                tvTabIndex.setText("历史客户");
                initCalendar(this.baseCalendar);
                setCrmView(null);
                break;
            case R.id.topBack:
                finish();
                break;
        }

    }

    @Override
    public void showLoaidng() {
        if (dialog != null && !dialog.isShowing()) {

            dialog.show();
            //List<User> users = udao.queryConstants(enterpriseCode, userId);
            //Log.i("test","数据库查询："+users.size());
        }
       // progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoading() {
        if (dialog != null && dialog.isShowing()) {

            dialog.dismiss();
            //List<User> users = udao.queryConstants(enterpriseCode, userId);
            //Log.i("test","数据库查询："+users.size());
        }
       // progressBar.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onCrmlistSuccess(List<CrmCalendarListBean.ListBean> datalist) {
        this.crmList = datalist;
        //calendarAdapter.setList(dateList, dataCunt, tagIndex,workDate);
        setCrmView(datalist);
    }

    @Override
    public void onCountSuccess(List<CrmCalendarCountBean.DataList> data) {
        this.dataCunt = data;
        Log.i("test", "数据设置日期：" + workDate);
        calendarAdapter.setList(dateList, data, tagIndex,workDate);
    }

    @Override
    public void onFailed() {

    }

    @Override
    public void onExpertion() {

    }
}
